package com.cxh.rmsq.ui.fragment.self

import android.app.Dialog
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.net.newNet.TreasureViewModel
import com.cxh.rmsq.ui.activity.self.ClueListActivity
import com.cxh.rmsq.ui.activity.self.JoinRecordActivity
import com.cxh.rmsq.ui.activity.self.PublishCommunityActivity
import com.cxh.rmsq.ui.activity.self.RankListActivity
import com.cxh.rmsq.ui.adapter.self.InviteListAdapter
import com.cxh.rmsq.ui.adapter.self.RankListAdapter
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.ui.widget.MapContainer
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.dialog.CluePopup
import com.cxh.rmsq.utils.dialog.PlayActivityPopup
import com.google.gson.Gson
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.shape.layout.ShapeRelativeLayout
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.rong.callkit.util.SPUtils
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale


/**
 * 寻宝
 */
class PlayCircleFragment : BaseFragment(), View.OnClickListener {
    private lateinit var refreshLayout: SmartRefreshLayout
    private lateinit var mScrollView: NestedScrollView
    private lateinit var map_container: MapContainer
    private lateinit var tv_name: TextView
    private lateinit var tv_time: TextView
    private lateinit var tv_desc: TextView
    private lateinit var tv_all_money: TextView
    private lateinit var tv_exchange_price: TextView
    private lateinit var tv_join_record: TextView
    private lateinit var tv_necessary: TextView
    private lateinit var tv_all_rank: TextView
    private lateinit var tv_activity_time: TextView
    private lateinit var tv_reset: TextView
    private lateinit var mapview: MapView
    private lateinit var rv_list: RecyclerView
    private lateinit var ll_rank: LinearLayout
    private lateinit var container: LinearLayout
    private lateinit var srl_map: ShapeRelativeLayout
    private lateinit var rl_title: RelativeLayout
    private var page = 1
    private var statusActivity = 1
    private var startTime: Long = 0
    private var endTime: Long = 0
    var activityId = ""
    var rank = ""
    var progressId = ""
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(TreasureViewModel::class.java)
    }

    private var aMap: AMap? = null
    private var markers = mutableListOf<Marker>()

    //声明mLocationClient对象
    var mLocationClient: AMapLocationClient? = null

    //声明mLocationOption对象
    var mLocationOption: AMapLocationClientOption? = null

    override fun getLayoutResId(): Int {
        return R.layout.fragment_play_circle
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
        mScrollView = view.findViewById(R.id.nestedScrollView) as NestedScrollView
        map_container = view.findViewById(R.id.map_container) as MapContainer
        tv_name = view.findViewById(R.id.tv_name) as TextView
        tv_time = view.findViewById(R.id.tv_time) as TextView
        tv_all_money = view.findViewById(R.id.tv_all_money) as TextView
        tv_join_record = view.findViewById(R.id.tv_join_record) as TextView
        tv_exchange_price = view.findViewById(R.id.tv_exchange_price) as TextView
        tv_desc = view.findViewById(R.id.tv_desc) as TextView
        tv_necessary = view.findViewById(R.id.tv_necessary) as TextView
        tv_all_rank = view.findViewById(R.id.tv_all_rank) as TextView
        tv_activity_time = view.findViewById(R.id.tv_activity_time) as TextView
        tv_reset = view.findViewById(R.id.tv_reset) as TextView
        mapview = view.findViewById(R.id.mapview) as MapView
        rv_list = view.findViewById(R.id.rv_list) as RecyclerView
        ll_rank = view.findViewById(R.id.ll_rank) as LinearLayout
        container = view.findViewById(R.id.amount_container) as LinearLayout
        srl_map = view.findViewById(R.id.srl_map) as ShapeRelativeLayout
        rl_title = view.findViewById(R.id.rl_title) as RelativeLayout

        map_container.setScrollView(mScrollView);
        tv_join_record.setOnClickListener(this)
        tv_necessary.setOnClickListener(this)
        tv_all_rank.setOnClickListener(this)
        tv_reset.setOnClickListener(this)

        initLocation()
        getLocationData()

        tv_desc.text = "1.点击碎片进入碎片详情，获取免费线索或购买付费线索\n" +
                "2.到达碎片地点后，拍照打卡并上传定位\n" +
                "3.集齐3个地图碎片后，兑换现金奖励50元\n" +
                "4.集齐5个地图碎片后，兑换现金奖励80元\n" +
                "5.抽取到三碎片地图的概率为70%，抽取到五碎片地图的概率为30%\n" +
                "6.当期活动内，用户可进行多次地图收集活动\n" +
                "7.当期活动到达结束时间后，进行中的任务立即失效，请在活动进行时完成您的地图收集任务\n" +
                "8.活动主办方：本活动由【济南诚信华网络科技有限公司】独立承办，与其它无关\n" +
                "9.本活动最终解释权归【济南诚信华网络科技有限公司】所有"

        mapview.onCreate(savedInstanceState)
        aMap = mapview.getMap()

        // 移除缩放控件
        aMap!!.uiSettings.isZoomControlsEnabled = false
        // 禁止手势缩放
        aMap!!.uiSettings.isZoomGesturesEnabled = false

        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setEnableRefresh(true)
        refreshLayout.setRefreshHeader(MaterialHeader(activity))
        refreshLayout.setRefreshFooter(ClassicsFooter(activity))
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {

            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshLayout.finishRefresh()
                initData()
            }
        })
    }

    override fun onInitView(savedInstanceState: Bundle?, intent: Intent?) {

    }

    private fun initData() {
        viewModel.getAppHunt { it ->
            if (it.code == 200 && it.data != null) {
                activityId = it.data.id.toString()
                statusActivity = it.data.status
                tv_name.text = it.data.name
                tv_all_money.text = it.data.poolAmount
                if (!TextUtils.isEmpty(it.data.remainingPoolAmount)) {
                    formatAmountWithStyle(it.data.remainingPoolAmount!!.toDouble())
                }
                startTime = it.data.startDate
                endTime = it.data.endDate
                tv_activity_time.isVisible = true
                srl_map.isVisible = true
                rl_title.isVisible = true
//                val spannedText = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    Html.fromHtml(it.data.description, Html.FROM_HTML_MODE_COMPACT)
//                } else {
//                    Html.fromHtml(it.data.description)
//                }
//
//                tv_desc.text = spannedText
//                tv_desc.movementMethod = LinkMovementMethod.getInstance() // 支持链接点击
                tv_activity_time.text =
                    "活动时间：" + TimeUtils.millis2String(
                        startTime,
                        "yyyy-MM-dd"
                    ) + "~" + TimeUtils.millis2String(
                        endTime, "yyyy-MM-dd"
                    )
                tv_time.text = "剩余活动时间：" + TimeUtils.getFitTimeSpan(
                    it.data.endDate,
                    System.currentTimeMillis(),
                    3
                )
                // 移除所有旧 Marker
                markers.forEach { it.remove() }
                markers.clear()
                viewModel.getMapProgress(it.data.id) {
                    if (it.code == 200) {
                        rl_title.isVisible = true
                        srl_map.isVisible = true
                        val array = Gson().fromJson(it.data.fragmentIds, Array<Int>::class.java)
                        progressId = it.data.id.toString()

                        if (it.data.orTc == "1") {//弹窗
                            activityNecessaryPop()
                        }
                        viewModel.getHuntLocation(array) {
                            if (it.code == 200) {
                                if (it.data.size > 0) {
                                    val points: MutableList<LatLng> = ArrayList()
                                    points.clear()
                                    for (i in 0 until it.data.size) {
                                        points.add(
                                            LatLng(
                                                it.data[i].latitude!!,
                                                it.data[i].longitude!!
                                            )
                                        )
                                    }
                                    points.forEachIndexed { pos, latLng ->
                                        if (1 == it.data[pos].userLocationStatus) {
                                            val marker = aMap!!.addMarker(
                                                MarkerOptions()
                                                    .position(latLng)
                                                    .title(it.data[pos].locationCode)
                                                    .snippet(it.data[pos].id.toString())
                                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_custom_marker))
                                            )
                                            val customData = hashMapOf(
                                                "userLocationStatus" to it.data[pos].userLocationStatus,
                                                "distance" to it.data[pos].checkInRadius,
                                                "latitude" to it.data[pos].latitude,
                                                "longitude" to it.data[pos].longitude
                                            )
                                            marker.setObject(customData)
                                            markers.add(marker)
                                        } else {
                                            val marker = aMap!!.addMarker(
                                                MarkerOptions()
                                                    .position(latLng)
                                                    .title(it.data[pos].locationCode)
                                                    .snippet(it.data[pos].id.toString())
                                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_custom_marker_none))
                                            )
                                            val customData = hashMapOf(
                                                "userLocationStatus" to it.data[pos].userLocationStatus,
                                                "distance" to it.data[pos].checkInRadius,
                                                "latitude" to it.data[pos].latitude,
                                                "longitude" to it.data[pos].longitude
                                            )
                                            marker.setObject(customData)
                                            markers.add(marker)
                                        }

                                    }

                                    // 提取所有经纬度
                                    val latLngList = markers.map { it.position }

                                    // 计算地理边界
                                    val builder = LatLngBounds.builder()
                                    latLngList.forEach { builder.include(it) }
                                    val bounds = builder.build()

                                    // 调整地图显示区域（边距 100 像素）
                                    val padding = 100
                                    val cameraUpdate = CameraUpdateFactory.newLatLngBoundsRect(
                                        bounds,
                                        padding,
                                        padding,
                                        padding,
                                        padding
                                    )
                                    aMap!!.animateCamera(cameraUpdate)
                                    // 默认聚焦到第一个点（可选）
//                                    if (!points.isEmpty()) {
//                                        aMap!!.moveCamera(
//                                            CameraUpdateFactory.newLatLngZoom(
//                                                points.get(0),
//                                                12F
//                                            )
//                                        )
//                                    }

                                    aMap!!.setOnMarkerClickListener { marker -> // 显示信息窗口
                                        // marker.showInfoWindow()
//                                    ToastUtils.showShort("碎片:" + marker.title)
                                        //userLocationStatus 1 已打卡 0 未打卡
                                        val data = marker.`object` as? HashMap<*, *>
                                        data?.let {
                                            val userLocationStatus = it["userLocationStatus"] as Int
                                            val distance = it["distance"] as Int
                                            val latitude = it["latitude"] as Double
                                            val longitude = it["longitude"] as Double
                                            // 处理数据（例如跳转页面）
                                            if (1 == userLocationStatus) {
                                                com.cxh.rmsq.utils.ToastUtils.showToast("当前碎片已打过卡！")
                                            } else {
                                                requireActivity().startActivity(
                                                    Intent(activity, ClueListActivity::class.java)
                                                        .putExtra("locationId", marker.snippet)
                                                        .putExtra("name", marker.title)
                                                        .putExtra(
                                                            "activityName",
                                                            tv_name.text.toString().trim()
                                                        )
                                                        .putExtra(
                                                            "progressId",
                                                            progressId.toString()
                                                        )
                                                        .putExtra("distance", distance)
                                                        .putExtra("latitude", latitude)
                                                        .putExtra("longitude", longitude)
                                                        .putExtra("activityId", activityId)
                                                )
                                            }
                                        }


                                        true
                                    }
                                } else {
                                    com.cxh.rmsq.utils.ToastUtils.showToast("暂无碎片信息")
                                }
                            }
                        }
                    } else {
                        com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
                        rl_title.isVisible = false
                        srl_map.isVisible = false
                    }
                }
            } else {
                tv_time.text = "活动暂未开启"
                formatAmountWithStyle(0.0)
                srl_map.isVisible = false
                rl_title.isVisible = false
                tv_activity_time.isVisible = false
            }
        }

        viewModel.getExchangeRanking(page, 10) {
            if (it.code == 200) {
                rank = it.data.data!!.userRank.toString()
                if (!TextUtils.isEmpty(it.data.data!!.amountEarned)) {
                    tv_exchange_price.text = it.data.data!!.amountEarned
                } else {
                    tv_exchange_price.text = "0"
                }
                if (it.data.list!!.size > 0) {
                    ll_rank.isVisible = true
                    tv_all_rank.isVisible = false
//                    tv_all_rank.isVisible = it.data.total > 10 //暂时隐藏
                    rv_list.setLayoutManager(LinearLayoutManager(activity))
                    var listAdapter = RankListAdapter(1)
                    listAdapter!!.setEmptyView(
                        View.inflate(
                            activity,
                            R.layout.empty_data_layout,
                            null
                        )
                    )

                    rv_list.setAdapter(listAdapter)
                    listAdapter.setNewInstance(it.data.list!!)
                } else {
                    ll_rank.isVisible = false
                }
            } else {
                com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_join_record -> {
                requireActivity().startActivity(
                    Intent(
                        requireActivity(),
                        JoinRecordActivity::class.java
                    )
                )
            }

            R.id.tv_necessary -> {
                activityNecessaryPop()
            }

            R.id.tv_all_rank -> {//排行榜
                requireActivity().startActivity(
                    Intent(
                        requireActivity(),
                        RankListActivity::class.java
                    )
                        .putExtra("rank", rank)
                )
            }

            R.id.tv_reset -> {//重置
                XPopup.Builder(activity)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .asCustom(
                        CluePopup(requireContext(),
                            7,
                            "",
                            object : CluePopup.onClick {
                                override fun click(s: String, s1: String) {
                                    viewModel.getDeleteMapProgress(progressId) {
                                        if (it.code == 200) {
                                            initData()
                                        } else {
                                            com.cxh.rmsq.utils.ToastUtils.showToast(it.msg.toString())
                                        }
                                    }
                                }
                            })
                    )
                    .show()
            }
        }
    }

    private fun activityNecessaryPop() {
        XPopup.Builder(activity)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(
                PlayActivityPopup(
                    requireActivity(),
                    startTime,
                    endTime,
                    object : PlayActivityPopup.onClick {
                        override fun click(s: String, s1: String) {

                        }
                    })
            )
            .show()
    }

    fun formatAmountWithStyle(amount: Double) {
//        val decimalFormat = DecimalFormat("###0.00", DecimalFormatSymbols(Locale.CHINA))
        val decimalFormat = DecimalFormat("###0", DecimalFormatSymbols(Locale.CHINA))
        val formatted = decimalFormat.format(amount)

        container.removeAllViews() // 清除旧内容

        val decimalIndex = formatted.indexOf('.') // 获取小数点位置

        formatted.forEachIndexed { index, char ->
            val isDecimalPart = index > decimalIndex && decimalIndex != -1

            val textView = TextView(activity).apply {
                text = char.toString()
                textSize = if (isDecimalPart) 20f else 30f // 小数部分字体更小
                setTypeface(null, Typeface.BOLD) // 关键代码
                setTextColor(Color.WHITE)

                // 仅数字添加背景
                if (char.isDigit()) {
                    background =
                        ContextCompat.getDrawable(context, R.mipmap.icon_treasure_price_bac)
                    setPadding(8.dpToPx(), 4.dpToPx(), 8.dpToPx(), 4.dpToPx())
                }

                // 调整间距
                val params = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply { marginEnd = 12.dpToPx() }
                layoutParams = params
            }

            container.addView(textView)
        }
    }

    // 扩展函数：dp 转像素
    fun Int.dpToPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()


    private fun initLocation() {
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption!!.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption!!.isOnceLocation = true
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption!!.isOnceLocationLatest = true
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption!!.isNeedAddress = true
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption!!.isMockEnable = true
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption!!.interval = 1000
        //设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption!!.httpTimeOut = 20000
        //关闭缓存机制
        mLocationOption!!.isLocationCacheEnable = false
        try {
            mLocationClient = AMapLocationClient(activity)
            //给定位客户端对象设置定位参数
            mLocationClient!!.setLocationOption(mLocationOption)
            mLocationClient!!.setLocationListener { aMapLocation ->
                //获取定位结果
                if (aMapLocation != null) {
                    if (aMapLocation.errorCode == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        if (!TextUtils.isEmpty(aMapLocation.city)) {
                            var address =
                                /*aMapLocation.getCity() + "" + aMapLocation.getDistrict() + "" +*/
                                aMapLocation.address

                            Log.e("address", address)
                        } else {

                            com.cxh.rmsq.utils.ToastUtils.showToast("未获取到城市名称，请重试")
                        }
                        dismissLoadingDialog()
                    } else {

                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        if (aMapLocation.errorCode == 12) {
                            com.cxh.rmsq.utils.ToastUtils.showToast("定位失败:" + "请在设置中打开定位服务开关后重试")
                        } else {
                            com.cxh.rmsq.utils.ToastUtils.showToast("定位失败:" + aMapLocation.errorInfo)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }


    //获取定位权限
    private fun getLocationData() {
        //应用上架要求添加权限使用说明
        val permissionInfoDialog = Dialog(requireContext())
        CustomPermissionUtil.showPermissionInfo(
            requireActivity(), permissionInfoDialog,
            resources.getString(R.string.permission_info_title_location_camp_clock),
            resources.getString(R.string.permission_info_content_location_camp_clock)
        )

        //获取定位权限并进行定位
        XXPermissions.with(this)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    if (allGranted) {
                        permissionInfoDialog.dismiss()

                        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                        mLocationClient!!.stopLocation()
                        mLocationClient!!.startLocation()
                    }
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    permissionInfoDialog.dismiss()

//                    com.cxh.rmsq.utils.ToastUtils.showToast(resources.getString(R.string.permission_set_location_camp_clock))
                    //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
//                    CustomPermissionUtil.showPermissionSet(
//                        activity,
//                        resources.getString(R.string.permission_set_location_camp_clock),
//                        permissions
//                    ) { //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
//                        mLocationClient!!.stopLocation()
//                        mLocationClient!!.startLocation()
//                    }
                }
            })

    }

    override fun onResume() {
        super.onResume()
        initData()
        mapview.onResume()
    }

    override fun onPause() {
        super.onPause()
        mapview.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
//        mapview.onDestroy();
        markers.clear();
        mLocationClient!!.stopLocation() //停止定位后，本地定位服务并不会被销毁
        mLocationClient!!.onDestroy() //销毁定位客户端，同时销毁本地定位服务。
    }
}